import React, { useEffect, useState } from "react";
import marked from "marked";
import "../style/editor.css";
// http
import http from "../api/axios"
// antd
import { Row, Col, Input, Select, Button, DatePicker,message } from "antd";
// axios
import axios from "../api/axios";
// Url
import Url from "../api/url"
const { Option } = Select;
const { TextArea } = Input;

function Editor(props) {
  const [articleId, setArticleId] = useState(0); // 文  章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [articleTitle, setArticleTitle] = useState(""); //文章标题
  const [articleContent, setArticleContent] = useState(""); //markdown的编辑内容
  const [markdownContent, setMarkdownContent] = useState("预览内容"); //html内容
  const [introducemd, setIntroducemd] = useState(); //简介的markdown内容
  const [introducehtml, setIntroducehtml] = useState("等待编辑"); //简介的html内容
  const [showDate, setShowDate] = useState(); //发布日期
  const [updateDate, setUpdateDate] = useState(); //修改日志的日期
  const [typeInfo, setTypeInfo] = useState([]); // 文章类别信息
  const [selectedType, setSelectType] = useState("选择分类"); //选择的文章类别

  const [typeList,setTypeList] = useState([])


  const SaveAritcle =function(){
    if(!Number.parseInt(selectedType)){
      message.error('必须选择文章类别') 
      return false
  }else if(!articleTitle){
      message.error('文章名称不能为空')
      return false
  }else if(!articleContent){
      message.error('文章内容不能为空')
      return false
  }else if(!introducemd){
      message.error('简介不能为空')
      return false
  }else if(!showDate){
      message.error('发布日期不能为空')
      return false
  }
  message.success('检验通过')
  let data ={ //添加文章
    article_data:{
      type_id:selectedType,
      title:articleTitle,
      article_content:articleContent,
      introduce:introducemd,
      create_time:showDate,
      id:articleId
    }
  }
  if(articleId==0){
    axios.post(Url.add,data).then(res=>{
      setArticleId(res.data.insertId)
      message.success("添加成功，当前状态为修改")
    }).catch(()=>{
        message.error("添加失败")
    })

  }else{ //修改文章
    axios.post(Url.update,data).then(res=>{
      setArticleId(res.data.insertId)
      message.success("添加成功，当前状态为修改")
    }).catch(()=>{
        message.error("修改失败")
    })
  }
  }



  marked.setOptions({
    renderer: marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
  });

  const changeContent = (e) => {
    setArticleContent(e.target.value);
    let html = marked(e.target.value);
    setMarkdownContent(html);
  };

  const changeIntroduce = (e) => {
    setIntroducemd(e.target.value);
    let html = marked(e.target.value);
    setIntroducehtml(html);
  };
const getTypeInfo=()=>{
  http.get(Url.typeInfo).then(res=>{
    if(res.data.state){
        setTypeList(res.data.data)
    }else{
      message.error(res.data.data)
    }
  })
}

const getOneById =  (id)=>{
    axios.get(Url.getArticleById,{id:id}).then(res=>{
      let {
        type_id,
        title,
        article_content,
        introduce,
        create_time,
      } = res.data.data[0]
      let html = marked(article_content);
      setMarkdownContent(html);

      let introducehtml = marked(introduce);
      setIntroducehtml(introducehtml);

      setSelectType(type_id)
      setArticleTitle(title)
      setArticleContent(article_content)
      setIntroducemd(introduce)
      setShowDate(create_time)
    }) 
}
 useEffect(()=>{
  if(props.location.query&&props.location.query.id){
    setArticleId(props.location.query.id)
    getOneById(props.location.query.id)
  } 
  getTypeInfo()
 },[])


  return (
    <div>
      <Row gutter={5}>
        <Col span={18}>
          <Row gutter={10}>
            <Col span={20}>
              <Input placeholder="博客标题" size="large" value={articleTitle} onChange={(e)=>{
                setArticleTitle(e.target.value)
              }}/>
            </Col>
            <Col span={4}>
              &nbsp;
              <Select defaultValue={selectedType} size="large"  onChange={(e)=>{setSelectType(e)}}>
                {typeList.map(Item=>{
                 return(<Option value={Item.id} key={Item.id} >{Item.type_name}</Option>)
                })}
              </Select>
            </Col>
          </Row>
          <br />
          <Row gutter={10}>
            <Col span={12}>
              <TextArea
                value={articleContent}
                className="markdown-content"
                rows={35}
                onChange={changeContent}
                onPressEnter={changeContent}
                placeholder="文章内容"
              />
            </Col>
            <Col span={12}>
              <div
                className="show-html"
                dangerouslySetInnerHTML={{ __html: markdownContent }}
              ></div>
            </Col>
          </Row>
        </Col>

        <Col span={6}>
          <Row>
            <Col span={24}>
              <Button size="large">暂存文章</Button>&nbsp;
              <Button type="primary" size="large" onClick={SaveAritcle}>
                发布文章
              </Button>
              <br />
            </Col>
            <Col span={24}>
              <Col span={12}>
                <div className="date-select">
                  <DatePicker placeholder="发布日期" size="large"  onChange={(date,dateString)=>{
                      setShowDate(dateString)
                  }}/>
                </div>
              </Col>
              <br />
              <TextArea
                rows={4}
                value={introducemd}
                onChange={changeIntroduce}
                onPressEnter={changeIntroduce}
                placeholder="文章简介"
              />
              <div
                className="introduce-html"
                dangerouslySetInnerHTML={{
                  __html: "文章简介：" + introducehtml,
                }}
              ></div>
            </Col>
          </Row>
        </Col>
      </Row>
    </div>
  );
}

export default Editor;
